from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import logging
# from test_ import Test
# from test1_ import Test1
from test_yqtyAdd import test_yqtyAdd

# from test_yqtyDele import test_yqtyDele
# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='D:\\Python\\seleniumtest\\automation.log',
    filemode='a'
)
logger = logging.getLogger(__name__)


def login_to_system(driver, username, password):
    """登录系统的函数"""
    try:
        # 等待页面加载完成
        wait = WebDriverWait(driver, 20)

        # 先等待页面完全加载
        time.sleep(3)

        print("开始查找用户名输入框...")
        # 尝试使用不同的定位方式
        try:
            username_input = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='帐号']")))
            print("找到用户名输入框")
        except Exception as e:
            print(f"使用CSS选择器查找用户名输入框失败: {e}")
            # 尝试使用XPath
            username_input = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='账号']")))
            print("使用XPath找到用户名输入框")

        username_input.clear()
        username_input.send_keys(username)
        print("已输入用户名")

        print("开始查找密码输入框...")
        try:
            password_input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input.el-input__inner[placeholder='密码']")))
            print("找到密码输入框")
        except Exception as e:
            logger.warning(f"使用CSS选择器查找密码输入框失败: {e}")
            # 尝试使用XPath
            password_input = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='密码']")))
            print("使用XPath找到密码输入框")

        password_input.clear()
        password_input.send_keys(password)
        print("已输入密码")

        print("开始查找登录按钮...")
        driver.find_element(By.CSS_SELECTOR, ".el-button--primary > span").click()
        # 尝试多种可能的选择器

        print("已点击登录按钮")

        # 增加等待登录成功的时间
        time.sleep(5)

        # 验证是否登录成功
        print(f"登录后页面标题: {driver.title}")
        return True

    except Exception as e:
        logger.error(f"登录过程中出现错误: {e}")
        # 保存截图以便调试
        try:
            screenshot_path = f"D:\\Python\\seleniumtest\\error_{int(time.time())}.png"
            driver.save_screenshot(screenshot_path)
            print(f"已保存错误截图到 {screenshot_path}")
        except:
            pass
        return False


def print_hi(name):
    """主函数"""
    service = ChromeService("D:/Chorme/chromedriver-win64/chromedriver-win64/chromedriver.exe")
    options = webdriver.ChromeOptions()
    # 添加一些选项以提高稳定性
    options.add_argument("--start-maximized")
    options.add_argument("--disable-extensions")

    driver = None
    try:
        driver = webdriver.Chrome(service=service, options=options)
        driver.get("https://jltest.ejclims.com/")
        print(f"页面标题: {driver.title}")

        # 调用登录函数
        login_success = login_to_system(driver, "admin_lims_jlzj", "20241219+-*/Bjxryjc!@#")

        if login_success:
            # 登录成功后的操作
            print("登录成功，开始执行测试...")
            # 创建Test实例并传入已登录的driver
            test_instance = test_yqtyAdd(driver)
            # 调用test_方法执行测试
            test_success = test_instance.test_yqtyAdd()

            if test_success:
                print("测试操作执行成功")
            else:
                print("测试操作执行失败")
            # 这里可以添加更多的测试步骤
            # 例如：导航到特定页面、填写表单、验证元素等

            # 示例：等待一段时间以便观察
            time.sleep(10)

    except Exception as e:
        logger.error(f"测试过程中出现错误: {e}")
    finally:
        # 确保浏览器最终会关闭
        if driver:
            driver.quit()
            print("浏览器已关闭")


# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print_hi('PyCharm')









url = '/html/body/div[25]/div[1]/div[1]/ul/li[1]'
url = 'body > div.el-select-dropdown el-popper > div.el-scrollbar > div.el-select-dropdown__wrap el-scrollbar__wrap > ul.el-scrollbar__view el-select-dropdown__list > li'